<template>
  <div :class="{'mobile-notice': showMobilePage}" class="flyNotice">
    <DataDisplay :data-list="statisticsList" class="mb16 mobile-data" />
    <div class="flex-center tab-wrap">
      <ListTab
        v-if="showMobilePage"
        v-model="tabStatus"
        :show-header="false"
        :tabs="tabs"
        :max-badge="{ num: 10000, str: '1w', unit:'+'}"
        class="tabs"
        @tabClick="handleTabClick" />
      <DetailTabs v-else v-model="tabStatus" :tabs="tabs" :max-badge="{ num: 10000, str: '1w', unit:'+'}" @tabClick="handleTabClick"/>
      <div class="filter-wrap">
        <FilterInput
          v-if="showMobilePage"
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          show-mobile-icon
          class="filter-btn"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
      </div>
    </div>
    <div class="flyNotice-list">
      <div class="filter">
        <FilterInput
          v-if="!showMobilePage"
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          class="filter-btn"
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus" />
        <div v-if="showMobilePage" :class="{'notice-btn-group':showNoticeBtn || isCreator}">
          <template v-if="showNoticeBtn">
            <el-button size="small" @click="additional">追加说明</el-button>
            <el-button size="small" @click="additionalAccount">追加账号</el-button>
            <el-button size="small" @click="pressSend">催办</el-button>
          </template>
          <btnGroup
            ref="btnGroupRef"
            :list="[
              {label:'导出', exportApi:'/admin/queryOrder/advise/export', exportName:'通知人员', beforeExport: exportBeforeExport, type: 'export'}
            ]"
            class="btns"
            style="margin-left:16px"
            @onComplate="exportonComplate"
          />
        </div>
        <template v-else>
          <template v-if="showNoticeBtn">
            <el-button size="small" @click="additional">追加说明</el-button>
            <el-button size="small" @click="additionalAccount">追加账号</el-button>
            <el-button size="small" @click="pressSend">催办</el-button>
          </template>
          <btnGroup
            ref="btnGroupRef"
            :list="[
              {label:'导出', exportApi:'/admin/queryOrder/advise/export', exportName:'通知人员', beforeExport: exportBeforeExport, type: 'export'}
            ]"
            class="btns"
            style="margin-left:16px"
            @onComplate="exportonComplate"
          />
        </template>
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 100px;">
          <u-table
            v-show="list.items.length"
            ref="tableRef"
            :data="list.items"
            :row-height="49"
            :row-class-name="tableRowClassName"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @sort-change="sortMethod"
            @select-all="selectTable">
            <u-table-column
              :fixed="useFixed"
              align="center"
              type="selection"
              width="50"
            />
            <u-table-column :fixed="useFixed" align="left" label="姓名">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.wxUserName" />
              </template>
            </u-table-column>
            <u-table-column :fixed="useFixed" align="left" label="账号" min-width="120">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.accountName" style="color:#406EFF;cursor:pointer" @click.native="toAccountDetail(scope.row.accountId)"/>
              </template>
            </u-table-column>
            <u-table-column align="left" label="下单平台" min-width="110">
              <template slot-scope="scope">
                <div class="flex-center" style="color: #999">
                  <platformIcon :data="scope.row.platformName" />
                  <ToolTip :content="scope.row.platformName" style="color: #333" />
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="粉丝量" min-width="110" sortable="custom" prop="fansNum">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.fansNum | numberTextFormat(1)" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="运营模式" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.operatingModelName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="标签" min-width="200">
              <template slot-scope="scope">
                <el-tooltip v-if="scope.row.tagName && scope.row.tagName.length" :open-delay="800" placement="top-start">
                  <div slot="content" style="max-width:300px">{{ handleStr(scope.row.tagName,'name') }}</div>
                  <div class="flex-center">
                    <span
                      v-for="(tag,index) in handleTags(scope.row.tagName)"
                      :key="index"
                      :style="tag.color ? `color:${tag.color};background:${changeColorAlphaVal(tag.color, 0.14)}` : ''"
                      class="tag">
                      {{ tag.name }}
                    </span>
                    <div v-if="scope.row.tagName.length > 3">...</div>
                  </div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="地域" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.region" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="接单偏好">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.orderPreference" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="微信号" min-width="110">
              <template slot-scope="scope">
                <SecretText :log-text="getLogText(scope.row.wxUserName, '微信号')" :origin-text="scope.row.wxCode" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="手机" min-width="110">
              <template slot-scope="scope">
                <SecretText :log-text="getLogText(scope.row.wxUserName, '手机')" :origin-text="scope.row.phone" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="响应状态" min-width="110">
              <template slot-scope="scope">
                <div class="status">
                  <div :class="`color-${scope.row.responsed.status}`" class="dot"/>
                  <div v-if="scope.row.responsed.status===0" class="text">待响应(<span :style="{color:scope.row.responsed.isRead?'#999999':'#406EFF'}">{{ `${scope.row.responsed.isRead?'已读':'未读'}` }}</span>)</div>
                  <div v-else>{{ scope.row.responsed.status | responseStatus }}</div>
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="追加次数">
              <template slot-scope="scope">
                <div>
                  <div v-if="scope.row.additionalTime === 0 || scope.row.additionalTime">{{ scope.row.additionalTime }}</div>
                  <div v-else>--</div>
                </div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="反馈记录" min-width="110">
              <template slot-scope="scope">
                <div v-if="scope.row.queryOrderFeedbacks && scope.row.queryOrderFeedbacks.length" class="checkBtn" @click="openRecordDialog(scope.row.queryOrderFeedbacks)">查看</div>
                <div v-else>--</div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder v-show="list.items.length === 0" slot="empty" empty-text="暂无数据" mode="border" style="margin-bottom: 24px" />
          <el-row v-show="list.items.length" type="flex" align="center">
            <div style="flex:1;display:flex;align-items:center;">
              <SelectionNum :select-item="multipleSelectionAll" style="flex:1;" @clearMixinSelection="clearMixinSelection" />
            </div>
            <el-pagination
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[10, 20, 50, 100, 250, 500]"
              :layout="showMobilePage?pageLayout:'total, prev, pager, next, sizes, jumper'"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </el-row>
        </div>
      </div>
    </div>
    <accountDialog
      ref="accountDialog"
      :query-order-id="queryOrderId"
      :show-submit-tip="false"
      is-notice
      show-notice-status
      btn-text="确认追加"
      @submit="addAccount"/>
    <additionalDialog ref="additionalDialog" :query-order-id="queryOrderId" @updateInfo="$emit('updateInfo')"/>
    <PressDialog ref="pressDialogRef" :query-order-id="queryOrderId"/>
    <recordDialog ref="recordDialog"/>
  </div>
</template>
<script>
import axios from 'axios';// 取消未完成请求
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import { TAG_MODULES } from '@/utils/const';
import { changeColorAlphaVal } from '@/utils/tools';
// 组件
import btnGroup from '@/components/Common/baseComponent/btnGroup';
import DetailTabs from '@/components/Common/baseComponent/DetailTabs';
import DataDisplay from '@/components/Common/baseComponent/dataDisplay';
import EmptyPlaceholder from '@/components/Common/emptyPlaceholder';
import accountDialog from './accountDialog';
import additionalDialog from './additionalDialog';
import PressDialog from './pressDialog';
import platformIcon from '@/components/Common/platformIcon';
import icon_19 from '@/assets/dataDisplay/icon_19.png';
import icon_44 from '@/assets/dataDisplay/icon_44.png';
import icon_12 from '@/assets/dataDisplay/icon_12.png';
import ListTab from '@/components/ListTab';
import recordDialog from './recordDialog';
// fitter
import { numberTextFormat } from '@/filters/number';
import { responseStatus } from '@/filters/status';
import { paramsRangeFormat, paramsAryToStr } from '@/utils/paramsFormat';
// api
import { getTagAll } from '@/api/config';
import { adviseabList, adviseList, additionalUser, getAdviseDashboard } from '@/api/flyNotice';
import { getOperateoptions } from '@/api/resource';
import { getDepartmentAll } from '@/api/config';
import { platformList } from '@/api/select';
import TableAdaptive from '@/mixins/tableAdaptive';
import tableSelections from '@/mixins/tableSelections';
import { allRegionData } from '@/utils/areaConfig';
import mobileTable from '@/mixins/mobileTable';

export default {
  components: {
    DetailTabs,
    EmptyPlaceholder,
    btnGroup,
    accountDialog,
    additionalDialog,
    PressDialog,
    platformIcon,
    ListTab,
    DataDisplay,
    recordDialog
  },
  filters: {
    responseStatus,
    numberTextFormat
  },
  mixins: [TableAdaptive, tableSelections, mobileTable],
  props: {
    queryOrderId: {
      type: Number,
      default: -1
    },
    showNoticeBtn: {
      type: Boolean,
      default: true
    },
    isCreator: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      TAG_MODULES,
      tabs: [],
      list: {
        items: [],
        total: 0
      },
      sortName: '',
      sortType: '',
      isUmyTable: true,
      idKey: 'id', // 多选框参数
      tableRefName: 'tableRef',
      tabStatus: -1,
      page: 1,
      perPage: 10,
      paramsObj: {},
      listLoading: false,
      deptTreeList: [],
      orderPlatformOption: [],
      tagTreeList: [],
      responsed: [
        { value: 0, label: '待响应' },
        { value: 1, label: '感兴趣' },
        { value: 2, label: '暂不考虑' }
      ],
      readOptions: [
        { value: 0, label: '未读' },
        { value: 1, label: '已读' }
      ],
      rangeKeyArr: [{
        attr: 'fansNum',
        start: 'fansNumStart',
        end: 'fansNumEnd',
        type: 'fansNums'
      }],
      statisticsData: {
        numberOfClosedAccounts: null,
        numberOfInquiryAccounts: null,
        accountConversionRate: null
      },
      orderFormOption: [],
      cancelToken: null,
      operateModeList: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      const arr = [
        // 输入框
        { keyword: 'wxUserName', name: '姓名', labelWidth: '70px', type: 'input' },
        { keyword: 'accountName', name: '账号', labelWidth: '100px', type: 'input' },
        { keyword: 'fansNum', name: '粉丝量', labelWidth: '70px', onlyInteger: true, type: 'inputRange', isRequired: true, startPlaceholder: '最低粉丝量', endPlaceholder: '最高粉丝量', max: 999999999 },
        { keyword: 'orderPreference', name: '接单偏好', labelWidth: '100px', type: 'input' },
        // 下拉
        { keyword: 'platformId', name: '下单平台', type: 'select', options: this.orderPlatformOption },
        { keyword: 'tagName', name: '标签', valueName: 'id', labelName: 'name',
          childrenVal: 'item', type: 'cascaderSelect', checkStrictly: false, options: this.tagTreeList,
          multiple: true, filterable: true, collapseTags: true
        },
        {
          keyword: 'region', name: '地域', valueName: 'label', labelName: 'label', checkStrictly: false, separator: '-',
          childrenVal: 'children', type: 'cascaderSelect', options: allRegionData, emitPath: true, filterable: true
        },
        { keyword: 'responsed', name: '响应状态', type: 'select', options: this.responsed },
        { keyword: 'readStatus', name: '阅读状态', type: 'select', options: this.readOptions },
        {
          keyword: 'operateMode', name: '运营模式', valueName: 'value', labelName: 'label',
          childrenVal: 'children', type: 'cascaderSelect', options: this.operateModeList,
          multiple: true, filterable: true, collapseTags: true, checkStrictly: false
        }
      ];
      return arr;
    },
    statisticsList() {
      return [
        { data: this.statisticsData.numberOfClosedAccounts, label: '成交账号数', isMoney: false, icon: icon_12, iconSize: 16, tooltip: '该询单中的账号被订单所关联的次数' },
        { data: this.statisticsData.numberOfInquiryAccounts, label: '询单账号数', isMoney: false, icon: icon_19, tooltip: '本条询单问询账号总数' },
        { data: this.statisticsData.accountConversionRate, label: '转化率', isMoney: false, unit: '%', icon: icon_44, iconSize: 16, tooltip: '成交账号数/问询账号数' }
      ];
    }
  },
  watch: {
    list: {
      handler: function(data) {
        this.$nextTick(() => {
          if (this.setSelectRow) {
            this.setSelectRow(data.items);
          }
        });
      },
      deep: true
    }
  },
  created() {
    this.fetchData(true);
    this.queryDeptTreeList();
    this.platformList();
    this.queryTagTreeList();
    this.getOperateData();
  },
  methods: {
    hasRouteAuth,
    changeColorAlphaVal,
    getOperateData() {
      // 获取运营模式
      getOperateoptions().then(res => {
        this.operateModeList = res.data;
      });
    },
    tableRowClassName({ row, rowIndex }) {
      const baseClass = 'pointer';
      if (this.multipleSelectionAll && this.multipleSelectionAll.length > 0) {
        const ids = this.multipleSelectionAll.map(i => i[this.idKey]);
        return ids.includes(row[this.idKey]) ? `table-selected ${baseClass}` : baseClass;
      }
      return baseClass;
    },
    // 跳转账号详情
    toAccountDetail(id) {
      if (!this.hasRouteAuth('medium:resource:admin')) {
        this.$message.warning('暂无资源可读权限，请联系管理员开通');
        return;
      }
      if (id) {
        const url = this.$router.resolve({
          name: 'detailResource',
          params: { resourceId: id }
        });
        window.open(url.href, '_blank');
      }
    },
    exportonComplate() {
      this.$emit('updateInfo');
    },
    updateInfo() {
      this.fetchData(true);
      this.$refs['accountDialog'].fetchData(true);
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.queryClick();
    },
    handleStr(arr = [], key) {
      let str = arr.map(el => el[key]).join(',');
      if (key === 'feedback') {
        str = str.replace(/<br>/g, '\n');
      }
      return str;
    },
    handleTags(tag = []) {
      if (!tag || tag.length === 0) {
        return [];
      }
      return tag.slice(0, 3);
    },
    // 导出
    exportBeforeExport() {
      const params = this.fomatParams();
      if (this.multipleSelectionAll.length > 0) {
        params.ids = this.multipleSelectionAll.map(el => el.id).join(',');
      }
      this.$refs['btnGroupRef'] && this.$refs['btnGroupRef'].btnExport(params);
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        result.data.forEach((i) => {
          i.label = i.value;
          i.value = i.id;
        });
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取部门列表
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    // 标签
    queryTagTreeList() {
      const params = { type: this.TAG_MODULES.RESOURCE };
      getTagAll(params).then(res => {
        this.tagTreeList = (res && res.data) || [];
        this.tagTreeList.forEach(item => {
          if (!item.item) item.disabled = true;
        });
      }).catch(e => {
        console.log(e);
      });
    },
    getTabs() {
      const params = this.fomatParams({});
      adviseabList(params).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.tabs = res.data;
      }).catch(err => {
        console.log(err);
      });
    },
    // 统计数据
    queryAdviseDashboard() {
      const params = this.fomatParams();
      getAdviseDashboard(params).then(res => {
        if (res.code === 200) {
          this.statisticsData = res.data;
        }
      }).catch(err => {
        console.log(err);
      });
    },
    fetchData(reset = false) {
      if (!this.queryOrderId || isNaN(this.queryOrderId)) {
        process.env.ENV_FORMAL && console.log('无效询单id');
        return;
      }
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();// 用于取消请求
      this.cancelToken = source;
      this.getTabs();
      this.queryAdviseDashboard();
      this.listLoading = true;
      if (reset) this.page = 1;
      const params = this.fomatParams(params);
      adviseList(params, source.token).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    fomatParams() {
      const params = {
        page: this.page,
        perPage: this.perPage,
        tabStatus: this.tabStatus
      };
      const paramsObj = Object.assign({}, this.paramsObj);
      paramsRangeFormat(this.rangeKeyArr, paramsObj);
      paramsAryToStr(['operateMode', 'tagName', 'region'], paramsObj);
      Object.keys(paramsObj).forEach(key => {
        if (paramsObj[key] || paramsObj[key] === 0) {
          params[key] = paramsObj[key];
        }
      });
      // status会为0
      if (paramsObj.status === 0) {
        params.status = 0;
      }
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      params.queryOrderId = this.queryOrderId;
      return params;
    },
    // 追加账号
    additionalAccount() {
      this.$refs['accountDialog'].openDrawer();
    },
    // 催办
    pressSend() {
      if (!this.multipleSelectionAll.length) {
        this.$message.warning('请选择需要催办的账号');
        return;
      }
      const ids = this.multipleSelectionAll.map(el => el.id).join(',');
      this.$nextTick(() => {
        this.$refs['pressDialogRef'].openDialog(ids);
      });
    },
    addAccount(list = []) {
      const data = {
        id: this.queryOrderId,
        queryOrderAdvises: []
      };
      if (list && list.length) {
        list.forEach(el => {
          data.queryOrderAdvises.push({
            wxUserId: el.wxUserId,
            accountId: el.accountId,
            accountName: el.accountName
          });
        });
        additionalUser(data).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.message);
            return;
          }
          this.$refs['accountDialog'].handleClose();
          this.$emit('updateInfo');
        }).catch(err => {
          console.log(err);
        });
      }
    },
    // 追加说明
    additional() {
      if (!this.multipleSelectionAll.length) {
        this.$message.warning('请选择需要追加说明的账号');
        return;
      }
      const ids = this.multipleSelectionAll.map(el => el.id).join(',');
      this.$nextTick(() => {
        this.$refs['additionalDialog'].openDialog(ids);
      });
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.clearMixinSelection();
      this.fetchData(true);
    },
    toEdit() {
      this.$router.push({
        name: 'flyNoticeEdit',
        params: {
          id: this.id
        }
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.sortName = '';
      this.sortType = '';
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    getLogText(name, label) {
      return `飞来通告通知人员 ${name}的${label}`;
    },
    openRecordDialog(list = []) {
      this.$refs.recordDialog.openDialog(list);
    }
  }
};
</script>
<style lang="scss" scoped>
$bgc: #FD8546 0, #31CC9C 1, #999 2;
  .mobile-notice {
    .filter {
      flex-wrap: wrap;
    }
    .tab-wrap {
      border-bottom: 1px solid #ddd;
    }
    .filter-wrap {
      padding-left: 8px;
    }
    .filter-btn {
      box-shadow: -5px 2px 8px -3px #dde1ea;
      ::v-deep .mobile-icon {
        margin: 0 !important;
        padding: 6px 0 4px 8px;
        box-shadow: unset;
        .text {
          display: none;
        }
      }
    }
    .notice-btn-group {
      display: flex;
    }
  }
  .tabs {
    padding-left: 0 !important;
    flex: 1;
    height: unset !important;
    ::v-deep .list-tab {
      padding-left: 0 !important;
    }
  }
	.flyNotice{
    .flyNotice-list{
      margin-top: 12px;
    }
    .operate{
      display: flex;
      align-items: center;
    }
    .border-left {
      position: relative;
      padding-left:6px;
      margin-left: 6px;
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        margin-top: -7px;
        width: 1px;
        background: #ddd;
        height: 14px;
      }
    }
		.filter {
			display: flex;
			align-items: center;
      margin-bottom: 16px;
      ::v-deep .el-button {
        padding-left: 12px;
        padding-right: 12px;
      }
		}
    .status{
      display: flex;
      align-items: center;
      position: relative;
      .text{
        white-space: nowrap;
      }
      .dot {
        position: absolute;
        left: -8px;
        display: inline-block;
        width: 4px;
        height: 4px;
        border-radius: 50%;
        @each $c, $i in $bgc {
          &.color-#{$i} {
            background: $c;
          }
        }
      }
    }
    .btns{
      ::v-deep {
        .fb-button-item{
          white-space: nowrap !important;
        }
      }
    }
    .ellipsis{/* 单行溢出隐藏 */
      width: 110px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .pointer{
      cursor: pointer;
    }
    .tag{
      display: inline-block;
      max-width: 60px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      color:#406EFF;
      font-size: 12px;
      padding: 0px 8px;
      background: #eff4ff;
      border-radius: 10px;
      margin-right: 4px;
    }
    .checkBtn {
      width: 60px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: white;
      background: #406EFF;
      padding: 4px 0;
      border-radius: 8px;
    }
    .checkBtn:hover {
      opacity: .8;
    }
	}
</style>
